const common = require("../common/common");

const formatTime = date => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};

const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n
};

const type = any => Function.prototype.call.bind(Object.prototype.toString)(any);

/**
 * 根据经纬度取得位置中文信息
 */
const qqMapUrlCN = (latitude,
                    longitude) => 'http://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=UZEBZ-56XLX-TR54J-73IBB-RVFZ2-47FF2';

/**
 * 根据位置中文取得经纬度
 */
const qqMapUrlDegree = text => 'http://apis.map.qq.com/ws/geocoder/v1/?address=' + text + '&key=UZEBZ-56XLX-TR54J-73IBB-RVFZ2-47FF2';

/**
 * 封装网络请求
 */
function sentHttpRequestToServer(uri, data, method, successCallback, failCallback, completeCallback) {
    wx.request({
        url: common.domain + common.prefixUrl + uri,
        data: data,
        method: method,
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: successCallback,
        fail: failCallback,
        complete: completeCallback
    })
}

/**
 * 弹窗提示成功
 */
function toastSuccess() {
    wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000
    })
}

/**
 * wxPromisify
 * @fn 传入的函数，如wx.request、wx.download
 */
function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
                resolve(res)
            };

            obj.fail = function (res) {
                reject(res)
            };

            fn(obj)//执行函数，obj为传入函数的参数
        })
    }
}

module.exports = {
    wxPromisify: wxPromisify
};

module.exports = {
    formatTime: formatTime,
    type: type,
    qqMapUrlCN: qqMapUrlCN,
    qqMapUrlDegree: qqMapUrlDegree,
    sentHttpRequestToServer: sentHttpRequestToServer,
    toastSuccess: toastSuccess,
    wxPromisify: wxPromisify,
};
